import select
import socket
import binascii
from bdtime import tt
import tools


HOST = ''
PORT = 8888

server_fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_fd.bind((HOST, PORT))
print('starting up on %s port %s' % (HOST, PORT))

# 把服务器套接字加入到输入列表中
# inputs = [server_fd]
rlist = [server_fd]
rdata = {}  # 存放客户端发送过来的消息
wlist=[]  # 等待写对象
wdata={}  # 存放要返回给客户端的消息

client_address_ls = []

# client_address = None
conn = None

while True:
    if tt.now(0) % 5 == 0:
        print(f'tt.now: {tt.now(1)}, len(client_address_ls): {len(client_address_ls)}')

    # readable, writable, exceptional = select.select(inputs, [], [], 1.0)
    # rl = select.select(rlist, [], [], 1.0)[0]
    rl, wl, xl = select.select(rlist, [], [], 1)

    for s in rl:
        data, client_address = s.recvfrom(1024)

        if data and data not in [b'0', b'exit']:
            recv_msg = tools.decode(data)
            # 收到客户端数据
            print('received "%s" from %s, --- tt.now: %s' % (recv_msg, client_address, tt.now(1)))

            # print(data)
            # tools.send_close_msg(s, client_address)
            # s.sendto(data, client_address)
            # wdata[client_address] = data

            wdata[client_address] = data
            if client_address not in wlist:
                wlist.append(client_address)

            if client_address not in client_address_ls:
                client_address_ls.append(client_address)
            # client_address_ls.append(client_address)
        else:
            # 相当于关闭这个链接
            client_address_ls.remove(client_address)

    for client_address in client_address_ls:
        # 这个客户端没消息就pass掉
        if client_address not in wdata:
            continue

        # --- to self
        # sock.send(wdata[client_address])
        msg = tools.encode(b'Response|' + wdata[client_address])

        # tools.send_to(server_fd, msg, client_address)
        server_fd.sendto(msg, client_address)

        # # --- broadcast
        # for conn in connected_channels_ls:
        #     conn.send(wdata[sock])
        #     # conn.send("这是广播~\n".encode('utf-8'))

        # wlist.remove(client_address)
        wdata.pop(client_address)

